﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.IO;
using System.Text;
using System;

public class AssetBuild 
{
    public static string assetPath = "Prefabs";//需要打包的路径
    public static List<string> assetPathList = new List<string>();//需要打包的资源路径
    public static string assetOutPutPath="/Users/GaoShi/Documents" + "/Resources";
    //需要打包的资源后缀
    private static Dictionary<string, string> asExtensionDic = new Dictionary<string, string>();

    [MenuItem("AssetManager/AssetBuild")]
    public static void BuildAsset()
    {
        string outputPath=Path.Combine(assetOutPutPath,Plathform.GetPlatformFolder(EditorUserBuildSettings.activeBuildTarget));
        SatrtBuild(outputPath);
    }
    public static void SatrtBuild(string outPath)
    {
       
        //如果不存在到处路径文件，创建一个
        if (!Directory.Exists(outPath))
        {
            Directory.CreateDirectory(outPath);
        }

        //打包
       // BuildPipeline.BuildAssetBundles(outPath, 0, EditorUserBuildSettings.activeBuildTarget);
        BuildPipeline.BuildAssetBundles(outPath, BuildAssetBundleOptions.None, EditorUserBuildSettings.activeBuildTarget);
       
        AssetDatabase.Refresh();
        CreatVersionText(outPath);
    }

    //遍历制定文件夹获取需要打包的资源路径
    private static void GetDirs(string dirPath)
    {
        foreach (string path in Directory.GetFiles(dirPath))
        {
            // 通过资源后缀判断资源是否为需要打包的资源
            if (asExtensionDic.ContainsKey(System.IO.Path.GetExtension(path)))
            {
             // string   pathReplace = path.Replace('/', '\\');
                Debug.Log(path);
                string pathtmp = path.Substring(path.IndexOf("Assets/"));
                //通过资源路径来获取需要打包的资源
                AssetImporter assetImporter = AssetImporter.GetAtPath(pathtmp);
                // 从此处(assetPath = "AllAssets")截取路径  
                string assetName = path.Substring(path.IndexOf(assetPath));
                //替换后缀名
                assetName = assetName.Replace(Path.GetExtension(assetName), ".dat");
                assetImporter.assetBundleName = assetName;
               
               /* string pathReplace = "";

                // Windows 平台分隔符为 '/', OS 平台 路径分隔符为 '\'， 此处是一个大坑
				if (Application.platform == RuntimePlatform.OSXEditor)
                {
                    pathReplace = path.Replace('/', '\\');
                }
				Debug.Log(pathReplace);
                //将需要打包的资源路径添加到打包路劲中
				assetPathList.Add(pathReplace);*/
            }
        }

        if (Directory.GetDirectories(dirPath).Length > 0)  //遍历所有文件夹
        {
            foreach (string path in Directory.GetDirectories(dirPath))
            {
                //使用递归方法遍历所有文件夹
                GetDirs(path);
            }
        }
    } 
    //添加需要打包资源的后缀
    private static void SetASExtensionDic()
    {
        asExtensionDic.Clear();

        asExtensionDic.Add(".prefab", ".unity3d");
        asExtensionDic.Add(".mat", ".unity3d");
        asExtensionDic.Add(".png", ".unity3d");
        asExtensionDic.Add(".renderTexture", ".unity3d");
    }

    //清除已经打包的资源 AssetBundleNames
    [MenuItem("AssetManager/ClearAssetBundlesName")]
    public static void ClearAssetBundlesName()
    {
        int length = AssetDatabase.GetAllAssetBundleNames().Length;
        Debug.Log(length);
        string[] oldAssetBundleNames = new string[length];
        for (int i = 0; i < length; i++)
        {
            oldAssetBundleNames[i] = AssetDatabase.GetAllAssetBundleNames()[i];
        }

        for (int j = 0; j < oldAssetBundleNames.Length; j++)
        {
            AssetDatabase.RemoveAssetBundleName(oldAssetBundleNames[j], true);
        }
    }

    /// <summary>
    /// Marks the asset. :包名，后缀名
    /// </summary>
    [MenuItem("AssetManager/Mark")]
    public static void MarkAsset()
    {
        assetPathList.Clear();
        SetASExtensionDic();
        GetDirs(Application.dataPath + "/" + assetPath);
    }
    /// <summary>
    ///  生成资源md5值
    /// </summary>
    /// <param name="path">Path.</param>
    public static void CreatVersionText(string path)
    {
        string[] files = Directory.GetFiles(path, "*", SearchOption.AllDirectories);
        string tmpPath = path + "/";
        StringBuilder versions = new StringBuilder();
        for (int i = 0, len = files.Length; i < len; i++)
        {
            string filePath = files[i];
            string extension = "";
            if (files[i].Contains("."))
                extension = filePath.Substring(files[i].LastIndexOf('.'));
            else
                continue;
            if (extension == ".dat")
            {
                string relativePath = filePath.Replace(tmpPath, "").Replace("\\", "/");
                string md5 = MD5File(filePath);
                versions.Append(relativePath).Append(",").Append(md5).Append("\n");
            }
        }

        FileStream stream = new FileStream(path + "/version.txt", FileMode.Create);
        byte[] data = Encoding.UTF8.GetBytes((versions.ToString()));
        stream.Write(data, 0, data.Length);
        stream.Flush();
        stream.Close();
    }
    /// <summary>
    /// 生成MD5值
    /// </summary>
    /// <returns>The 5 file.</returns>
    /// <param name="file">File.</param>
	public static string MD5File(string file)
    {
        try
        {
            FileStream fs = new FileStream(file, FileMode.Open);
            System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
            byte[] retVal = md5.ComputeHash(fs);
            fs.Close();
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < retVal.Length; i++)
            {
                sb.Append(retVal[i].ToString("x2"));
            }
            return sb.ToString();

        }
        catch(Exception ex)
        {
            throw new System.Exception("md5file() fail,error:" + ex.Message);
        }
    }
}
//根据切换的平台返回相应的导出路径
public class Plathform
{
    public static string GetPlatformFolder(BuildTarget target)
    {
        switch (target)
        {
            case BuildTarget.Android:   //Android平台导出到 Android文件夹中
                return "Android";
            case BuildTarget.iOS:
                return "IOS";
            case BuildTarget.StandaloneWindows:
            case BuildTarget.StandaloneWindows64:
                return "Windows";
            case BuildTarget.StandaloneOSXIntel:
            case BuildTarget.StandaloneOSXIntel64:
            case BuildTarget.StandaloneOSX:
                return "OSX";
            default:
                return null;
        }
    }
}